<?php
namespace Admin\Controller;

class PostController extends CommonController
{
    // 帖子列表
    public function index()
    {
        $posts = M('Post')->select();
        
        $this->assign('posts', $posts);
        $this->display();
    }

    // 设置帖子状态：1：正常 0：隐藏
    public function status()
    {
        $pid = (int)I('get.pid');
        //var_dump($pid);die;
        if(!is_int($pid)) $this->error('PID参数无效');
        
        if(I('get.status') == 1) {
            M('Post')->where(['id'=>$pid])->setField('status', 1);
            $this->redirect('Post/index');
        } elseif (I('get.status') == 0) {
            M('Post')->where(['id'=>$pid])->setField('status', 0);
            $this->redirect('Post/index');
        } else {
            $this->error('URL参数无效');
        }
    }

    // 设置置顶
    public function settop()
    {
        $isTop = I('get.istop');
        //var_dump($isTop);die;
        if($isTop == 0) {
           $value = 1;
        } else {
           $value = 0;
        }
        
        M('Post')->where(['id'=>I('get.pid')])->setField('is_top', $value);
        $this->redirect('Post/index');
    }

















    // 设置加精
    public function setjing()
    {
        $isJing = I('get.isjing');
        if($isJing == 0) {
           $value = 1;
        } else {
           $value = 0;
        }
        
        M('Post')->where(['id'=>I('get.pid')])->setField('is_jing', $value);
        $this->redirect('Post/index');
    }

    public function delete()
    {
        $pid = I('get.pid');

        M()->startTrans(); // 开启事务

        $postRow = M('Post')->where(['id'=>$pid])->setField('status', '-1');
        $replyRow = M('Reply')->where(['pid'=>$pid])->setField('status', '-1');

        if($postRow === false || $replyRow === false) {
            M()->rollback(); // 失败时回滚
            $this->error('删帖失败');
        } else {
            M()->commit();   // 成功时提交
            $this->success("成功删除 {$postRow} 条贴子，同时删除 {$replyRow} 条评论");
        }
    }
}